#! /usr/bin/env python

from wheezy.template.engine import Engine
from wheezy.template.ext.core import CoreExtension
from wheezy.template.loader import FileLoader
from openpyxl import load_workbook
from optparse import OptionParser 
import copy, json,re, os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

typeRE=re.compile(r'[a-zA-Z]')

class MODULE:
    pass

class GROUP:
    pass

class TEST:
    pass

class CONFIG:
    pass

class TestEncoder(json.JSONEncoder):
    '''
        testcase object transfer to JSON
        '''
    def default(self, obj):
        d={}
        d.update(obj.__dict__)
        return d

parser = OptionParser()
# Flow Instruction
parser.add_option("-m", action="store", default=None, dest='Module', \
                  help="Give the module name which you want to generate the testplan ")
# File/Path
parser.add_option("--list", action="store_true", default=False, dest="List", \
                  help="List all the module in the interface files")

parser.add_option("-f", action="store", default=None, dest="File", \
                  help="give the file name of testplan")

parser.add_option("-d", "--debug", action="store_true", default=False, dest="Debug", \
                  help="enable debug mode")

parser.add_option("-t", "--template", action="store", default="lsu.template", dest="Template", \
                  help="specify the template files")

(option, args) = parser.parse_args()

assert option.File !=None, "Please specify a interface file for this tools"

wb = load_workbook(filename = option.File)
worklist = wb.get_sheet_names()
testhome = os.getcwd()

def GetModules(_name):
    sheet_ranges = wb[_name]
    column=len(sheet_ranges['A'])
    line=len(sheet_ranges['1'])
    item=sheet_ranges['1']
    assert  column != 0, "no contents in sheets column"
    assert  line != 0, "no contents in sheets line"

    __module = MODULE()

    setattr(__module, "name", "%s_testplan"%(_name.replace(" ", "_")))
    setattr(__module, "groups", {})

    # find the first testline

    for i in range(1, column):
      if sheet_ranges["B%s"%(i)].value == "Type":
         start_line = i
         break

    for i in range(start_line+1, column+1):
        test = sheet_ranges["C%s"%(i)].value
        group = sheet_ranges["E%s"%(i)].value

        if group not in __module.groups.keys():
          __module.groups[group] = GROUP() 
          setattr(__module.groups[group], "Name", group)
          setattr(__module.groups[group], "tests", {})

        __module.groups[group].tests[test] = TEST()

        setattr(__module.groups[group].tests[test], "Name", test)
        setattr(__module.groups[group].tests[test], "UVM_TESTNAME", sheet_ranges["G%s"%(i)].value)
        setattr(__module.groups[group].tests[test], "C_TESTNAME", sheet_ranges["H%s"%(i)].value)
        setattr(__module.groups[group].tests[test], "Description", sheet_ranges["I%s"%(i)].value)
        plusarg = sheet_ranges["F%s"%(i)].value
        print test
        if plusarg != None:
          setattr(__module.groups[group].tests[test], "Commands", [])
          plusargs= plusarg.split(";")
          for k in plusargs:
            #print k
            cfg = CONFIG()
            key = k.split("=")[0]
            value = k.split("=")[1]
            setattr(cfg, "Key", key.replace("\n", "").replace("\r", ""))
            setattr(cfg, "Value", value.replace("\n", "").replace("\r",""))
            if typeRE.search(value):
              setattr(cfg, "Type", "enum")
            else:
              setattr(cfg, "Type", "int")
            __module.groups[group].tests[test].Commands.append(copy.deepcopy(cfg))

    return __module

def Render(_group):
    global cwd
    searchpath = [testhome+'/templates']
    engine = Engine(
      loader = FileLoader(searchpath),
      extensions=[CoreExtension()]
    )
    template = engine.get_template(option.Template)

    __file = open("test.json", "w")
    content = template.render({"group":_group})
    __file.write(content)
    __file.close()

def Run():    
    if option.List:
      for i in worklist:
          if i not in ["README", "Summary"]:
            print i
    else :
        list_module = []
        if  option.Module != None: 
            assert option.Module in worklist
            list_module.append(GetModules(option.Module))
        else: 
            for i in worklist:
                list_moudle.append(GetModules(i))
    
        for i in list_module:
            __module = i
            assert len(__module.groups) != 0 , "no signals in module %s"%(__module.name)
            if option.Debug:
                __item = TestEncoder().encode(__module)
                print __item
            else:
              if os.path.exists("./testplan"):
                os.system("rm -rf ./testplan")
              os.mkdir("./testplan")
              os.chdir("./testplan")
              cwd=os.getcwd()
                 
              for i in __module.groups.keys():
                os.mkdir("./%s"%(i))
                os.chdir(os.getcwd()+"/%s"%(i))
                Render(__module.groups[i])
                os.chdir(cwd)


if __name__ == "__main__":
    Run()

